﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using GarageManagement.Common;

namespace GarageManagement.ServiceClient
{
    public interface IGmClient
    {
        T GetOne<T>(string route);
        IList<T> Get<T>(string route);
        bool Add<T>(string route, T entity);
        bool Edit<T>(string route, T entity);
        bool Delete(string route);
    }

    public class GmClient : IGmClient
    {
        private readonly HttpClient client;

        public GmClient()
        {
            client = new HttpClient
                {
                    BaseAddress = new Uri(Settings.BaseAddress)
                };

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public T GetOne<T>(string route)
        {
            var response = client.GetAsync(route).Result;

            return !response.IsSuccessStatusCode ? Activator.CreateInstance<T>() : response.Content.ReadAsAsync<T>().Result;
        }

        public IList<T> Get<T>(string route)
        {
            var response = client.GetAsync(route).Result;

            return !response.IsSuccessStatusCode ? null : response.Content.ReadAsAsync<IList<T>>().Result;
        }

        public bool Add<T>(string route, T entity)
        {
            var response = client.PostAsJsonAsync(route, entity).Result;

            return response.IsSuccessStatusCode;
        }

        public bool Edit<T>(string route, T entity)
        {
            var response = client.PutAsJsonAsync(route, entity).Result;

            return response.IsSuccessStatusCode;
        }

        public bool Delete(string route)
        {
            var response = client.DeleteAsync(route);

            return response.Result.IsSuccessStatusCode;
        }
    }
}
